<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\facade\Cache;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,photo,nickname,mobile,is_active,team_id,level_id,team_total,team_accumulate,second_total,my_accumulate');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,is_active,team_id,level_id,team_total,team_accumulate,second_total,my_accumulate')->with('level');
    }

    //第二市场业绩
    public static function second_total($u_id)
    {
        try {
            $list = parent::with('user')->where('new_uid', $u_id)->field('id,uid,algebra')->order('algebra', 'asc')->select();//团队列表
            foreach ($list as $r=>$item)
            {
                $zt_user = User::where(['parent_id' => $item->uid, 'is_active' => 2])->field('id,team_accumulate')->order('team_accumulate', 'desc')->limit(2)->select();//直推人员最大的
                if (isset($zt_user['1'])) {
                    User::update(['second_total' => $zt_user['1']->team_accumulate], ['id' => $item->uid]);//修改二市场业绩
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 原点 2020年8月22日16:25:27 记录推荐关系
     *
     * @param $uid -- 新会员ID
     * @param $code -- 新会员编号
     * @param $status -- 状态：默认0普通会员1正式会员
     * @param $parent_id -- 推荐人的ID
     * @return array
     */
    public function record($uid, $code, $parent_id, $status = 0)
    {
        try {
            $algebra = 1;
            $time = time();
            if ($parent_id) {
                $p_id = $parent_id;
                $insert = [];
                while ($parent = User::where('id', $p_id)->field('id,code,parent_id')->find()) {
                    if ($parent) {
                        $data['uid'] = $parent->id;
                        $data['code'] = $parent->code;
                        $data['new_uid'] = $uid;
                        $data['new_code'] = $code;
                        $data['algebra'] = $algebra;
                        $data['create_time'] = $time;
                        $data['status'] = $status;
                        $insert[] = $data;
                        $p_id = $parent->parent_id;
                    }
                    $algebra++;
                }
                $this->insertAll($insert);
            }
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        $all_id[] = $uid;
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }
    }

    public static function team_accumulate($amount, $uid, $key = 'team_accumulate')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        $all_id[] = $uid;
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }
    }


    //推荐奖
    public static function recommend_reward($uid,$amount): array
    {
        try {
            $list = parent::where('new_uid', $uid)->where('algebra','<=',3)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            foreach ($list as $k=>$v)
            {
                $tp_num = 'tp_'.$v->algebra;
                $tp = Cache::get('system')[$tp_num];
                $tp_reward = bcmul((string)$amount,(string)$tp,2);
                if($tp_reward>0)
                {
                    Target::Account()->basics($v->uid, 'bonus', $tp_reward, '推荐奖', '+')
                        ->createBonus($uid, 1);
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $tp_reward]);
                }

            }
            return ['code' => 1];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //直推奖
    public static function direct($uid,$amount): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
//            dump($list);die;
            $level_id = 0;
            $level_direct = 0;
            $level_reward = 0;
            $reward_id = 1;
            foreach ($list as $k=>$v)
            {
               if($v->user->level_id > $level_id)
               {
                   $level = Level::find($v->user->level_id);
                   $direct = $level->direct - $level_direct;
                   $reward = bcmul((string)$amount,(string)$direct,2);
                   Target::Account()->basics($v->uid, 'bonus', $reward, '直推奖', '+')
                       ->createBonus($uid, 2);
                   $level_id = $level->id;
                   $level_direct = $level->direct;
                   $level_reward = $reward;
               }elseif($v->user->level_id == $level_id&&$reward_id)
               {
                   $level = Level::find($v->user->level_id);
                   $equal = bcmul((string)$level_reward,(string)$level->equal,2);
                   Target::Account()->basics($v->uid, 'bonus', $equal, '直推平级', '+')
                       ->createBonus($uid, 7);
                   $reward_id = 0;
               }
            }
            return ['code' => 1];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //间推奖
    public static function indirect($user,$pid,$amount): array
    {
        try {
            $p_user = User::find($pid);
            if($p_user->parent_id)
            {
                $p_p_user = User::find($p_user->parent_id);
                $p_p_level = Level::find($p_p_user->level_id);
                $indirect = bcmul((string)$amount,(string)$p_p_level->indirect,2);
                if($indirect>0)
                {
                    Target::Account()->basics($user->parent_id, 'bonus', $indirect, '间推奖', '+')
                        ->createBonus($user->id, 3);
                    Event::trigger('Statistics', ['key' => 'expend', 'value' => $indirect]);
                }
            }
            return ['code' => 1];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $uid
     * @param $total
     * @return array|int[]
     * 原点 2023年7月12日14:16:53 团队奖
     */
    public static function teamBonus(): array
    {
        try {
            $list = User::where('team_total','>',0)->where(['delete_time'=>0])->where('team_id','>',0)->where('level_id','>=',6)->order('id','asc')->select();
            $expendTotal = 0;
            foreach ($list as $k=>$v)
            {
                $user_team_level = TeamLevel::find($v->team_id);
                $reference = User::where(['parent_id'=>$v->id,'delete_time'=>0])->where('team_total','>',0)->where('team_id','>',0)->where('level_id','>=',6)->select();
                $team_total = 0;
                foreach ($reference as $key=>$value)
                {
                    $team_level = TeamLevel::find($value->team_id);
                    if($user_team_level->id > $team_level->id)
                    {
                        $team_reward = $user_team_level->team_reward - $team_level->team_reward;
                        $reward = bcmul((string)$value->team_total,(string)$team_reward,2);
                        if($reward>0)
                        {
                            Target::Account()->basics($v->id, 'bonus', $reward, '团队奖', '+')
                                ->createBonus($v->id, 4);
                            Relation::level_reward($v->id,$reward,$user_team_level);
                            $expendTotal+=$reward;
                        }
                    }
                    $team_total+=$value->team_total;
                }
                $my_team_reward = $v->team_total - $team_total;
                $my_reward = bcmul((string)$my_team_reward,(string)$user_team_level->team_reward,2);
                if($my_reward>0)
                {
                    Target::Account()->basics($v->id, 'bonus', $my_reward, '团队奖', '+')
                        ->createBonus($v->id, 4);
                    Relation::level_reward($v->id,$my_reward,$user_team_level);
                    $expendTotal+=$my_reward;
                }

                User::where('id',$v->id)->update(['last_team_total'=>$v->team_total]);
            }
//            User::where('id','<>',0)->update(['team_id'=>0]);
            if ($expendTotal > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
            }
            return ['code' => 1, 'msg' => '发奖成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //平级奖
    public static function level_reward($uid,$my_team_reward,$user_team_level)
    {
        $list = parent::with('user')->where('new_uid', $uid)
            ->field('id,uid,algebra')->order('algebra', 'asc')->select();
        $level_id = $user_team_level->id;
        $is_reward = 1;
        $expendTotal = 0;
        foreach ($list as $r=>$item)
        {
            if($item->user->team_id>$level_id)
            {
                $level_id = $item->team_id;
            }elseif($level_id==$item->user->team_id&&$is_reward){
                $p_reward = bcmul((string)$my_team_reward,(string)$user_team_level->level_reward,2);
                if($p_reward>0)
                {
                    Target::Account()->basics($item->uid, 'bonus', $p_reward, '平级奖', '+')
                        ->createBonus($uid, 5);
                    $expendTotal+=$p_reward;
                    $is_reward = 0;
                }

            }
        }
        if ($expendTotal > 0) {
            Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
        }
    }

    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid,$real_amount): array
    {
        try {
            $user = User::find($uid);
            $user_level = Level::where('id', '>',$user->level_id)
                ->where('disposable', '<=', $real_amount)
                ->order('id', 'desc')
                ->find();
            if ($user_level) {
                User::update(['level_id' => $user_level->id, 'id' => $uid]);
            }

            $user = User::find($uid);
            $user_level2 = Level::where('id', '>',$user->level_id)
                ->where('accumulate', '<=', $user->team_accumulate)
                ->where('performance', '<=', $user->second_total)
                ->order('id', 'desc')
                ->find();
            if ($user_level2) {
                User::update(['level_id' => $user_level2->id, 'id' => $uid]);
            }

            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            foreach ($list as $item) {
                 $level = Level::where('id', '>',$item->user->level_id)
                    ->where('accumulate', '<=', $item->user->team_accumulate)
                    ->where('performance', '<=', $item->user->second_total)
                    ->order('id', 'desc')
                    ->find();
                if ($level) {
                    User::update(['level_id' => $level->id, 'id' => $item->uid]);
                }
            }

            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 团队升级
     */
    public static function team_upgrade($uid): array
    {
        try {
            $user = User::find($uid);
            $user_level = TeamLevel::where('id', '>', $user->team_id)
                ->where('team_total', '<=', $user->team_total)
                ->order('id', 'desc')
                ->find();
            if ($user_level) {
                User::update(['team_id' => $user_level->id, 'id' => $uid]);
            }

            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $level = TeamLevel::where('id', '>', $item->user->team_id)
                    ->where('team_total', '<=', $item->user->team_total)
                    ->order('id', 'desc')
                    ->find();
                if ($level) {
                    User::update(['team_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    public static function recommend($p_uid,$boxes_num,$uid)
    {
        try {
            $repurchase_1 = Cache::get('system')['repurchase_1'];
            $amounts = bcmul((string)$repurchase_1, (string)$boxes_num, 2);
            Relation::awardPrizes($p_uid,$amounts,'复购奖', '+',$uid, 6);
            $p_user = User::where('id',$p_uid)->find();
            if($p_user->parent_id)
            {
                $repurchase_2 = Cache::get('system')['repurchase_2'];
                $amounts_2 = bcmul((string)$repurchase_2, (string)$boxes_num, 2);
                Relation::awardPrizes($p_user->parent_id,$amounts_2,'复购奖', '+',$uid, 6);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }



    public static function coaching_award($u_id,$amount)
    {
        try {
            $user = User::find($u_id);
            $users = User::where(['parent_id'=>$user->id,'is_active'=>2])->column('id');
            if($users)
            {
                $coaching_award_1= Cache::get('system')['coaching_award_1'];
                $num = count($users);
                $coaching_amount = bcmul((string)$amount,(string)$coaching_award_1,2);
                $amounts = bcdiv($coaching_amount, (string)$num,2);
                foreach ($users as $k=>$v)
                {
                    Relation::awardPrizes($v,$amounts,'辅导奖', '+',$user->id, 5);
                }
            }

            if($user->parent_id)
            {
                $p_user = User::where('id',$user->parent_id)->find();
                $p_num = User::where('parent_id',$p_user->id)->count();
                $coaching_award_2 = Cache::get('system')['coaching_award_2'];
                if ($p_num>=$coaching_award_2)
                {
                    $coaching_award_4 = Cache::get('system')['coaching_award_4'];
                    $coaching_amount_2 = bcmul((string)$amount,(string)$coaching_award_4,2);
                    Relation::awardPrizes($p_user->id,$coaching_amount_2,'辅导奖', '+',$user->id, 5);
                }

                if($p_user->parent_id)
                {
                    $pp_num = User::where('parent_id',$p_user->parent_id)->count();
                    $coaching_award_3 = Cache::get('system')['coaching_award_3'];
                    if ($pp_num>=$coaching_award_3)
                    {
                        $coaching_award_5 = Cache::get('system')['coaching_award_5'];
                        $coaching_amount_3 = bcmul((string)$amount,(string)$coaching_award_5,2);
                        Relation::awardPrizes($p_user->parent_id,$coaching_amount_3,'辅导奖', '+',$user->id, 5);
                    }

                }
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }

    //服务费
    public static function service_charge($recommend_shop,$num,$uid)
    {
        try {
            $service_charge= Cache::get('system')['service_charge'];
            $amount = bcmul((string)$service_charge,(string)$num,2);
            Relation::awardPrizes($recommend_shop,$amount,'服务费', '+',$uid, 7);
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    //分红
    public static function bonus()
    {
       $my_total = User::where('my_total','>',0)->sum('my_total');
       $expendTotal = 0;
       if($my_total)
       {
           $weighting_bonus_1= Cache::get('system')['weighting_bonus_1'];
           $amount = bcmul((string)$my_total,(string)$weighting_bonus_1,2);

           $users = User::where(['level_id'=>6,'delete_time'=>0])->select();
           $team_totals = User::where(['level_id'=>6,'delete_time'=>0])->sum('team_total');
           if($users)
           {
               foreach ($users as $key=>$value)
               {
                   $amounts = bcmul((string)($value->team_total/$team_totals),(string)$amount,2);

                   Target::Account()->basics($value->id, 'bonus', $amounts, '分红', '+')
                       ->createBonus($value->id, 6);
                   $expendTotal+=$amounts;
               }
           }

           $weighting_bonus_2= Cache::get('system')['weighting_bonus_2'];
           $amount_2 = bcmul((string)$my_total,(string)$weighting_bonus_2,2);

           $users_2 = User::where(['level_id'=>5,'delete_time'=>0])->select();
           $team_totals_2 = User::where(['level_id'=>5,'delete_time'=>0])->sum('team_total');
           if($users_2)
           {
               foreach ($users_2 as $k=>$v)
               {
                   $amounts_2 = bcmul((string)($v->team_total/$team_totals_2),(string)$amount_2,2);

                   Target::Account()->basics($v->id, 'bonus', $amounts_2, '分红', '+')
                       ->createBonus($v->id, 6);
                   $expendTotal+=$amount_2;
               }
           }

//           User::where('my_total','>',0)->update(['my_total'=>0]);
//            User::where('team_accumulate','>',0)->update(['team_accumulate'=>0]);
           if ($expendTotal > 0) {
               Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
           }
       }
        return ['code' => 1, 'msg' => '分红成功'];
    }
}
